import store from '@/store'
import { h } from 'vue'
import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
const getRoute = (path, component, children) => {
  return children ? { path, component, children } : { path, component }
}

const routes = [
  // 首页
  getRoute('/', () => import('@/views/Layout.vue'), [
    getRoute('/', () => import('@/views/home')),
    getRoute('/category/:id', () => import('@/views/category')),
    getRoute('/category/sub/:id', () => import('@/views/category/sub.vue')),
    getRoute('/product/:id', () => import('@/views/goods')),
    getRoute('/member/checkout', () =>
      import('@/views/member/pay/checkout.vue'),
    ),
    getRoute('/member/pay/:id', () => import('@/views/member/pay')),
    getRoute('/member', () => import('@/views/member/Layout.vue'), [
      getRoute('/member', () => import('@/views/member/home')),
      getRoute('/member/order', { render: () => h(RouterView) }, [
        getRoute('', () => import('@/views/member/order')),
        getRoute(':id', () =>
          import('@/views/member/order/detail.vue'),
        ),
      ]),
    ]),
    getRoute('/pay/callback', () => import('@/views/member/pay/callback.vue')),
  ]),
  // login
  getRoute('/login', () => import('@/views/login')),
  getRoute('/login/callback', () => import('@/views/login/callback.vue')),
  // cart
  getRoute('/cart', () => import('@/views/cart')),
  // use
]

console.warn(
  'first',
  getRoute('/member', () => import('@/views/member/Layout.vue'), [
    getRoute('/member', () => import('@/views/member/home')),
    getRoute('/member/order', { render: () => h(<RouterView />) }, [
      getRoute('', () => import('@/views/member/order')),
      getRoute('/member/order:id', () => import('@/views/member/order/detail')),
    ]),
  ]),
)

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  },
})

router.beforeEach((to, from, next) => {
  if (!store.state.user.profile.token && to.path.startsWith('/member'))
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  next()
})

export default router
